package com.upu173.music.utils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;

import com.andbase.library.db.orm.dao.AbDBDao;
import com.andbase.library.db.orm.dao.AbDBDaoImpl;
import com.andbase.library.utils.AbDateUtil;
import com.andbase.library.utils.AbImageUtil;
import com.andbase.library.utils.AbLogUtil;
import com.andbase.library.utils.AbStrUtil;
import com.upu173.music.R;
import com.upu173.music.db.inside.DBInsideHelper;
import com.upu173.music.model.PlayList;
import com.upu173.music.model.Song;
import com.upu173.music.model.SongFolder;
import com.upu173.music.model.SongTag;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MusicUtil {

    public static List<Song> songList = new ArrayList<>();

    public static AbDBDao dao = null;

    /**
     * 扫描系统里面的音频文件，返回一个list集合
     * @param context
     * @return
     */
    public static List<Song> initSongList(Context context) {
        dao = new AbDBDaoImpl(DBInsideHelper.getInstance(context),Song.class);
        songList.clear();
        File sdFile = Environment.getExternalStorageDirectory();
        listFile(context,sdFile);

        List<String> sdFileExt = getExtSDCardPath();
        for(String path:sdFileExt){
            listFile(context,new File(path));
        }
        for(Song song:songList){
            song.setUpdateTime(AbDateUtil.getCurrentDate(AbDateUtil.dateFormatYMDHMS));
        }
        //插入到数据库中
        dao.startWritableDatabase();
        dao.deleteAll();
        dao.insertList(songList);
        dao.closeDatabase();

        return songList;
    }


    public static List<Song> getSongList(Context context) {
        dao = new AbDBDaoImpl(DBInsideHelper.getInstance(context),Song.class);
        songList.clear();
        dao.startReadableDatabase();
        List<Song> songListNew =  dao.queryList(null,null,
                new String[]{},null, null,"update_time asc", null);
        dao.closeDatabase();
        if(songListNew!=null){
            songList.addAll(songListNew);
        }
        return songList;
    }

    public static List<Song> getSongListFromFolder(Context context,String folderPath) {
        List<Song> songList = new ArrayList<>();
        dao = new AbDBDaoImpl(DBInsideHelper.getInstance(context),Song.class);
        dao.startReadableDatabase();
        List<Song> songListNew =  dao.queryList();
        dao.closeDatabase();

        for (int i = 0; i < songListNew.size(); i++) {
            Song song = songListNew.get(i);
            if (folderPath.equals(song.getParentPath())) {
                songList.add(song);
                AbLogUtil.i(context,"getSongListFromFolder Song:" + song.getPath());
            }
        }

        return songList;
    }

    public static List<PlayList> getPlayList(Context context) {
        dao = new AbDBDaoImpl(DBInsideHelper.getInstance(context),PlayList.class);
        dao.startReadableDatabase();
        List<PlayList> playLists =  dao.queryList(null,null,
                new String[]{},null, null,"update_time asc", null);
        dao.closeDatabase();
        return playLists;
    }

    public static void addPlayList(Context context,List<Song> songList) {
        List<PlayList> playListList = new ArrayList<>();
        for(Song song:songList){
            song.setUpdateTime(AbDateUtil.getCurrentDate(AbDateUtil.dateFormatYMDHMS));
            PlayList playList = new PlayList();
            playList.setName(song.getName());
            playList.setPath(song.getPath());
            playList.setParentPath(song.getParentPath());
            playList.setSinger(song.getSinger());
            playList.setSize(song.getSize());
            playList.setDuration(song.getDuration());
            playList.setUpdateTime(song.getUpdateTime());
            playListList.add(playList);
        }
        dao = new AbDBDaoImpl(DBInsideHelper.getInstance(context),PlayList.class);
        //插入到数据库中
        dao.startWritableDatabase();
        dao.insertList(playListList);
        dao.closeDatabase();
    }

    public static void updatePlayList(Context context,List<PlayList> playLists) {
        dao = new AbDBDaoImpl(DBInsideHelper.getInstance(context),PlayList.class);
        //插入到数据库中
        dao.startWritableDatabase();
        dao.deleteAll();
        dao.insertList(playLists);
        dao.closeDatabase();
    }

    public static void deletePlayList(Context context,int id) {
        dao = new AbDBDaoImpl(DBInsideHelper.getInstance(context),PlayList.class);
        //插入到数据库中
        dao.startWritableDatabase();
        dao.delete(id);
        dao.closeDatabase();
    }

    public static void clearPlayList(Context context) {
        dao = new AbDBDaoImpl(DBInsideHelper.getInstance(context),PlayList.class);
        //插入到数据库中
        dao.startWritableDatabase();
        dao.deleteAll();
        dao.closeDatabase();
    }

    /**
     * 按文件夹分组
     * @param songList
     * @return
     */
    public static ArrayList<SongFolder> groupByFolder(List<Song> songList) {
        Map<String, List<Song>> songListMap = new HashMap<>();

        for (int i = 0; i < songList.size(); i++) {
            Song song = songList.get(i);
            if (songListMap.containsKey(song.getParentPath())) {
                List<Song> folderList = songListMap.get(song.getParentPath());
                folderList.add(song);
            } else {
                List<Song> temp = new ArrayList<>();
                temp.add(song);
                songListMap.put(song.getParentPath(), temp);
            }
        }

        ArrayList<SongFolder> songFolderList = new ArrayList<>();

        for (Map.Entry<String,List<Song>> entry : songListMap.entrySet()) {
            SongFolder songFolder = new SongFolder();
            File file = new File(entry.getKey());
            songFolder.setName(file.getName());
            songFolder.setPath(entry.getKey());
            songFolder.setParentPath(file.getParent());
            songFolder.setCount(entry.getValue().size());
            songFolder.setSongList(entry.getValue());
            songFolderList.add(songFolder);
        }

        return songFolderList;
    }

    public static void listFile(Context context,File parent){
        File[] files = parent.listFiles();
        if(files == null){
            return;
        }
        for(File file:files){
            if(file.isDirectory() && !file.getName().startsWith(".")){
                listFile(context,file);
            }else{
                if(file.getName().toLowerCase().contains(".mp3") || file.getName().contains(".flac")) {
                    SongTag songTag = MusicUtil.getSongTag(context,file.getPath(),false);
                    Song song = new Song();
                    song.setName(songTag.getTitle()!=null?songTag.getTitle():file.getName());
                    song.setPath(file.getPath());
                    song.setSinger(songTag.getArtist());
                    song.setParentPath(file.getParent());
                    song.setSize(file.length());
                    songList.add(song);
                }
            }
        }

    }

    public static String timeToString(int time){
        int miniute = 0;
        int second = 0;
        int secondAll = time/1000;

        if(secondAll > 60){
            miniute = secondAll/60;
        }

        second = secondAll%60;

        String miniuteStr = AbStrUtil.strFormat2(String.valueOf(miniute));
        String secondStr = AbStrUtil.strFormat2(String.valueOf(second));

        return miniuteStr + ":" + secondStr;
    }

    public static SongTag getSongTag(Context context, String path,boolean album) {
        SongTag songTag = null;
        try{
            songTag = new SongTag();
            Uri selectedAudio = Uri.parse(path);
            MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
            mediaMetadataRetriever.setDataSource(context, selectedAudio);

            String title = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);
            songTag.setTitle(title);
            String artist = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
            songTag.setArtist(artist);

            if(album){
                byte[] embeddedPicture;
                embeddedPicture = mediaMetadataRetriever.getEmbeddedPicture();
                if (embeddedPicture != null && embeddedPicture.length < 1024 * 1000) {
                    Bitmap bitmap = BitmapFactory.decodeByteArray(embeddedPicture, 0, embeddedPicture.length);
                    songTag.setBitmap(bitmap);
                }
            }

        }catch (Exception e){
            e.printStackTrace();
        }

        return songTag;
    }

    /**
     * 获取外置SD卡路径
     */
    public static List<String> getExtSDCardPath(){
        List<String> result = new ArrayList<String>();
        try {
            Runtime runtime = Runtime.getRuntime();
            Process process = runtime.exec("mount");
            InputStream inputStream = process.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader br = new BufferedReader(inputStreamReader);
            String line;
            while ((line = br.readLine()) != null) {
                AbLogUtil.e("MusicUtil",line);
                if (line.contains("sdcard")){
                    String [] arr = line.split(" ");
                    String path = arr[1];
                    File file = new File(path);
                    if (file.isDirectory()){
                        result.add(path);
                    }
                }
            }
            inputStreamReader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

}
